//
//  HWGameCircleController.swift
//  HWanGame
//
//  Created by 王昌健 on 2021/12/30.
//

import UIKit
import JXSegmentedView
import ZLPhotoBrowser
import Kingfisher
class HWGameCircleController: HWBaseViewController {
    
    var collectionView:UICollectionView!
    let collectionProtocol = HWGameCircleProtocol()
    let httpManager = HWGameCircleHttpManager()
    var releaseButton:UIButton!
    var tempArr = NSMutableArray()
    var modelArr = NSMutableArray()
    var recommendArr = NSMutableArray()
    var isLoginGoBack = false
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
        loadData()
        
        addAction()
        
        addRefresh()
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if isLoginGoBack == true {
            loadData()
            isLoginGoBack = false
        }
        
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        releaseButton.isHidden = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        releaseButton.isHidden = true
    }
}
extension HWGameCircleController {
    private func initUI() -> Void {
        navigationView.isHidden = true
        view.backgroundColor = .clear
        
        let flowL = UICollectionViewFlowLayout.init()
        flowL.minimumLineSpacing = 3*widthScale
        flowL.minimumInteritemSpacing = 3*widthScale
        
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: flowL)
        collectionView.delegate = collectionProtocol
        collectionView.dataSource = collectionProtocol
        collectionView.showsVerticalScrollIndicator = false
        collectionView.backgroundColor = .white
        collectionView.register(HWGameCircleTopCell.self, forCellWithReuseIdentifier: "HWGameCircleTopCell")
        collectionView.register(HWGameCircleCell.self, forCellWithReuseIdentifier: "HWGameCircleCell")
        collectionView.register(HWGameCircleRecommendCell.self, forCellWithReuseIdentifier: "HWGameCircleRecommendCell")
        collectionView.register(HWGameCircleHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HWGameCircleHeader")
        collectionView.register(HWGameCircleFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "HWGameCircleFooter")
        view.addSubview(collectionView)
        collectionView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "暂无数据")
        collectionView.ly_emptyView.contentViewOffset = -40
        
        releaseButton = UIButton(type: .custom)
        releaseButton.setImage(UIImage(named: "releaseButton"), for: .normal)
        releaseButton.addTarget(self, action: #selector(releaseButtonClick(_:)), for: .touchUpInside)
        currentWindow?.rootViewController?.view.addSubview(releaseButton)
        let panGesture = UIPanGestureRecognizer(target: self, action:#selector(dragAction(gesture:)))
        releaseButton.addGestureRecognizer(panGesture)
        
        
        let config = ZLPhotoConfiguration.default()
        
        config.languageType = .chineseSimplified
        
        //        config.maxSelectCount = 9
        //        config.allowSelectGif = false
        //        config.allowMixSelect = false
        ////        config.allowSelectVideo =  images.count == 0
        //        config.allowTakePhotoInLibrary = true
        //        config.allowEditVideo = true
        //        config.maxEditVideoTime = 30
        //        config.maxRecordDuration = 30
        //        config.editAfterSelectThumbnailImage = true
        //        config.allowSelectOriginal = false
        //        config.animateSelectBtnWhenSelect = false
        //        config.cropVideoAfterSelectThumbnail = true
        
    }
    
    private func initFrame() -> Void {
        collectionView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalTo(0)
        }
        
        releaseButton.snp.makeConstraints { make in
            make.right.equalTo(-17*widthScale)
            make.width.height.equalTo(54*widthScale)
            make.bottom.equalTo(-200*widthScale)
        }
    }
}

extension HWGameCircleController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension HWGameCircleController {
    func loadData() -> Void {
        
        httpManager.getGameCircleGroup { models in
            
            self.collectionProtocol.groupModelArr = models
            self.collectionView.reloadData()
        } failure: { error in
            
        }
        
        
        let netGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "GameCircle")
        
        netGroup.enter()
        workingQueue.async {
            self.httpManager.getGameCircleList { models in
                if models.count > 0 {
                    self.modelArr.removeAllObjects()
                    self.modelArr.addObjects(from: models)
                }
                netGroup.leave()
            } failure: { error in
                netGroup.leave()
            }
        }
        
        netGroup.enter()
        workingQueue.async {
            self.httpManager.getGameCircleRecommend { models in
                netGroup.leave()
                if models.count > 0 {
                    self.recommendArr.removeAllObjects()
                    self.recommendArr.addObjects(from: models)
                }
            } failure: { error in
                netGroup.leave()
            }
        }
        
        netGroup.notify(queue: workingQueue) {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                self.collectionView.mj_header?.endRefreshing()
                self.collectionView.mj_footer?.endRefreshing()
                for mod in self.recommendArr {
                    (mod as! HWGameCircleModel).isRecommend = true
                    
                }
                for (index ,_) in self.modelArr.enumerated() {
                    if index % 3 == 0 && index > 0 {
                        
                        if self.recommendArr.count > index/3 - 1 {
                            self.modelArr.insert(self.recommendArr[index/3 - 1], at: index + index/3 - 1)
                        }
                    }
                }
                
                self.collectionProtocol.modelArr = self.modelArr as? [HWGameCircleModel]
                self.collectionView.reloadData()
            }
            
        }
        
        
    }
    
    func addRefresh() -> () {
        
        collectionView.mj_header = MJRefreshNormalHeader()
        collectionView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        collectionView.mj_footer = MJRefreshBackNormalFooter()
        collectionView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        self.collectionView.mj_footer?.endRefreshing()
        self.httpManager.getGameCircleListFooter { models in
            self.collectionView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.modelArr.addObjects(from: models)
            }
            self.collectionProtocol.modelArr = self.modelArr as? [HWGameCircleModel]
            self.collectionView.reloadData()
        } failure: { error in
            //            if error == "暂无房间"{
            //                self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            //            }else{
            self.collectionView.mj_footer?.endRefreshing()
            //            }
        }
        
    }
}

extension HWGameCircleController {
    func addAction() -> Void {
        collectionProtocol.didSelectImage = {
            index,images in
            var datas: [Any] = []
            for a in images {
                datas.append(URL(string: a)!)
            }
            let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
                
                return .image
            } urlImageLoader: { (url, imageView, progress, loadFinish) in
                imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                    let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                    debugPrint("\(percentage)")
                    progress(percentage)
                } completionHandler: { (_) in
                    loadFinish()
                }
            }
            
            vc.doneBlock = { (datas) in
                debugPrint(datas)
            }
            
            vc.modalPresentationStyle = .fullScreen
            self.showDetailViewController(vc, sender: nil)
            
        }
        
        collectionProtocol.didSelectVideo = {
            url in
            
            let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
                
                return .video
            } urlImageLoader: { (url, imageView, progress, loadFinish) in
                imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                    let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                    debugPrint("\(percentage)")
                    progress(percentage)
                } completionHandler: { (_) in
                    loadFinish()
                }
            }
            
            vc.doneBlock = { (datas) in
                debugPrint(datas)
            }
            
            vc.modalPresentationStyle = .fullScreen
            self.showDetailViewController(vc, sender: nil)
        }
        
        collectionProtocol.zanButtonClick = {
            id in
            if HWLocallyStoredData.getLoginUserID().count>0 {
                self.httpManager.setTakeALookZan(type: "0", id: id) { message in
                    self.loadData()
                } failure: { error in
                    
                }
            }else{
                
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
                loginController.goBack = {
                    self.isLoginGoBack = true
                }
                
            }
            
            
            
        }
        
        collectionProtocol.jumpToDetail = {
            mod in
            if HWLocallyStoredData.getLoginUserID().count>0{
                let detailController = HWTakeALookDetailController()
                //            detailController.superVCLive_uid = self.live_uid
                detailController.model = mod
                self.navigationController?.pushViewController(detailController, animated: true)
            }else{
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
                loginController.goBack = {
                    self.isLoginGoBack = true
                }
            }
            
        }
        
        collectionProtocol.jumpToUserDetail = {
            mod in
//                        let userDetailControler = HWUserDetailController()
//                        userDetailControler.live_uid = $0
//                        self.navigationController?.pushViewController(userDetailControler, animated: true)
        }
        
        /// 群组
        collectionProtocol.jumpToGroup = {
            url in
            if HWLocallyStoredData.getLoginUserID().count>0{
                let webVC = XMGWebViewController()
                webVC.isGroup = true
                webVC.url = URL(string: url)
                self.navigationController?.pushViewController(webVC, animated: true)
            }else{
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
                loginController.goBack = {
                    self.isLoginGoBack = true
                }
            }
        }
        
        collectionProtocol.jumpToGameDetail = {
            id in
            let gameDetail = HWGameDetailController()
            gameDetail.gameId = id
            self.navigationController?.pushViewController(gameDetail, animated: true)
        }
        
    }
    
    @objc func dragAction(gesture: UIPanGestureRecognizer) {
        
        // 移动状态
        let moveState = gesture.state
        switch moveState {
        case .began:
            break
        case .changed:
            // floatBtn 获取移动轨迹
            let point = gesture.translation(in: self.view)
            self.releaseButton.center = CGPoint(x: self.releaseButton.center.x + point.x, y: self.releaseButton.center.y + point.y)
            break
        case .ended:
            // floatBtn 移动结束吸边
            let point = gesture.translation(in: self.view)
            var newPoint = CGPoint(x: self.releaseButton.center.x +  point.x, y: self.releaseButton.center.y + point.y)
            if newPoint.x < screenWidth / 2.0 {
                newPoint.x = self.releaseButton.bounds.width/2 + 17*widthScale
            } else {
                newPoint.x = screenWidth - self.releaseButton.bounds.width/2 - 17*widthScale
            }
            if newPoint.y <= self.releaseButton.bounds.height/2 + 17*widthScale + navigationView.bounds.height{
                newPoint.y = self.releaseButton.bounds.height/2 + 17*widthScale + navigationView.bounds.height
            } else if newPoint.y >= self.view.bounds.height - self.releaseButton.bounds.height/2 - 17*widthScale {
                newPoint.y = self.view.bounds.height - self.releaseButton.bounds.height/2 - 17*widthScale
            }
            // 0.5秒 吸边动画
            UIView.animate(withDuration: 0.5) {
                self.releaseButton.center = newPoint
            }
            break
        default:
            break
        }
        // 重置 panGesture
        gesture.setTranslation(.zero, in: self.view)
    }
    
    @objc func releaseButtonClick(_:UIButton) -> Void {
        if HWLocallyStoredData.getLoginUserID().count>0{
            let releaseController = HWTakeALookReleaseController()
            releaseController.releaseCallBack = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(releaseController, animated: true)
        }else{
            let loginController = HWLoginController()
            self.navigationController?.pushViewController(loginController, animated: true)
            loginController.goBack = {
                self.isLoginGoBack = true
            }
        }
        
    }
    
}
//@"language":[HWjianzhiduiObject returnLanguageAcquisition]
